package com.renwei.yunlong.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.fingdo.statelayout.StateLayout;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.activity.news.MessageDealActivity;
import com.renwei.yunlong.activity.news.TranspaintActivity;
import com.renwei.yunlong.activity.work.PersonSelectActivity;
import com.renwei.yunlong.adapter.CompanySelectAdapter;
import com.renwei.yunlong.adapter.FriendCompanyAdapter;
import com.renwei.yunlong.adapter.NewsMsgAdapter;
import com.renwei.yunlong.adapter.ObjectSelectAdapter;
import com.renwei.yunlong.adapter.PersonSelectAdapter;
import com.renwei.yunlong.adapter.SortContactAdapter;
import com.renwei.yunlong.adapter.SpareSelectAdapter;
import com.renwei.yunlong.adapter.StartChatListAdapter;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CompanySelectBean;
import com.renwei.yunlong.bean.EmpInfoJsonBean;
import com.renwei.yunlong.bean.EnterpriseBean;
import com.renwei.yunlong.bean.EnterpriseOwnerBean;
import com.renwei.yunlong.bean.EnterpriseServiceBean;
import com.renwei.yunlong.bean.MsgBean;
import com.renwei.yunlong.bean.AssetSearchBean;
import com.renwei.yunlong.bean.ScannerAsset;
import com.renwei.yunlong.bean.SpareSearchBean;
import com.renwei.yunlong.bean.SponsorBean;
import com.renwei.yunlong.bean.contacts.AllContactBean;
import com.renwei.yunlong.bean.contacts.CompanyContactBean;
import com.renwei.yunlong.bean.contacts.Contact;
import com.renwei.yunlong.event.ChatListCloseEvent;
import com.renwei.yunlong.event.ContactCheckEvent;
import com.renwei.yunlong.global.AppHelper;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.CommonUtils;
import com.renwei.yunlong.utils.ContactPingyinComparator;
import com.renwei.yunlong.utils.ContactPinyinComparator;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.LogUtil;
import com.renwei.yunlong.utils.PinyinUtils;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UtilList;
import com.renwei.yunlong.view.SearchImage;
import com.zyf.fwms.commonlibrary.base.baseadapter.BaseRecyclerViewAdapter;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import io.rong.imkit.RongIM;
import io.rong.imkit.userInfoCache.RongUserInfoManager;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.Conversation;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

import static com.renwei.yunlong.activity.work.CompanySelectActivity.FROM_ASSIGNER;
import static com.renwei.yunlong.activity.work.CompanySelectActivity.FROM_DEALER;
import static com.renwei.yunlong.activity.work.CompanySelectActivity.FROM_SENDER;
import static com.renwei.yunlong.activity.work.PersonSelectActivity.FROM_COMPLAIN_DEAL;
import static com.renwei.yunlong.activity.work.PersonSelectActivity.FROM_LAUNCH;
import static com.renwei.yunlong.activity.work.PersonSelectActivity.FROM_PROBLEM_ASSIGN;

public class CommonSearchActivity extends BaseActivity implements TextView.OnEditorActionListener {
    private static int from_type;
    public static final int DURATION = 300;
    private static final int MESSAGE_SHOW_KEYBOARD = 1;
    private static final int MESSAGE_SHOW_EDIT = 2;
    private static final AccelerateDecelerateInterpolator DEFAULT_INTERPOLATOR = new AccelerateDecelerateInterpolator();
    private static final String SCALE_WIDTH = "SCALE_WIDTH";
    private static final String SCALE_HEIGHT = "SCALE_HEIGHT";
    private static final String TRANSITION_X = "TRANSITION_X";
    private static final String TRANSITION_Y = "TRANSITION_Y";
    public String ownerCode;
    @Bind(R.id.activity_search_img)
    SearchImage mImageView;
    @Bind(R.id.search_top_cancel)
    LinearLayout searchCancel;
    @Bind(R.id.search_content)
    EditText searchEdit;
    @Bind(R.id.activity_search_top)
    RelativeLayout searchTop;
    @Bind(R.id.activity_search_line)
    TextView searchLine;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.state_layout)
    StateLayout stateLayout;
    @Bind(R.id.listview)
    ListView listview;
    @Bind(R.id.btn_commit)
    Button btnCommit;
    @Bind(R.id.rlv_bottom_contact)
    RecyclerView rlvBottomContact;
    @Bind(R.id.pannel_bottom)
    RelativeLayout pannelBottom;
    private String thisCompanyType;
    private ContactPingyinComparator contactPingyinComparator;
    private SortContactAdapter sortContactAdapter;

    /**
     * 存储图片缩放比例和位移距离
     */
    private Bundle mScaleBundle = new Bundle();
    private Bundle mTransitionBundle = new Bundle();
    /**
     * 屏幕宽度和高度
     */
    private int mScreenWidth;
    private int mScreenHeight;
    /**
     * 上一个界面图片的宽度和高度
     */
    private int mOriginWidth;
    private int mOriginHeight;
    /**
     * 上一个界面图片的位置信息
     */
    private Rect mRect;
    private CompanySelectAdapter companySelectAdapter;
    private PersonSelectAdapter personSelectAdapter;
    private ObjectSelectAdapter objectSelectAdapter;
    private FriendCompanyAdapter friendCompanyAdapter;
    private SpareSelectAdapter spareSelectAdapter;
    //根据拼音来排列企业联系人下面的数据ListView里面的数据类
    private ContactPinyinComparator contactPinyinComparator;
    private StartChatListAdapter bottomListAdapter;
    private List<Contact> contactList;

    private int from;
    private String name;
    private String bindFlag;
    private String synCode;
    private String contractId;
    private String companyCode;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MESSAGE_SHOW_KEYBOARD:
                    CommonUtils.showKeyboard(mContext, searchEdit);
                    break;
                case MESSAGE_SHOW_EDIT:
                    mImageView.setVisibility(View.GONE);
                    searchTop.setVisibility(View.VISIBLE);
                    searchLine.setVisibility(View.VISIBLE);
                    searchEdit.requestFocus();
                    break;
                default:
                    break;
            }
        }
    };
    private NewsMsgAdapter newsMsgAdapter;
    private List<MsgBean.RowsBean> msgList;
    private String editSearch;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_search);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.black_top), 0);
        initView();
    }

    protected void initView() {
        // 获得屏幕尺寸
        getScreenSize();
        // 初始化场景
        initial();
        // 设置入场动画
        runEnterAnim();
        // 初始化 控件
        initWidget();
        //动态显示搜索结果
        showSearchResult();
    }

    private void initWidget() {
        from = getIntent().getExtras().getInt("from");
        Class clazz = (Class) getIntent().getExtras().getSerializable("class");
        name = clazz.getSimpleName();
        // 人员
        synCode = getIntent().getStringExtra("synCode");
        bindFlag = getIntent().getStringExtra("bindFlag");
        // 对象
        ownerCode = getIntent().getStringExtra("ownerCode");
        contractId = getIntent().getStringExtra("contractId");
        //好友企业
        companyCode = getIntent().getStringExtra("companyCode");
        from_type = getIntent().getIntExtra("from_type", 0);//代表默认从联系人页面条转过来的
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        //判断 从哪个地方跳入进来
        if ("CompanySelectActivity".equals(name)) {
            companySelectAdapter = new CompanySelectAdapter(this, companyType);
            companySelectAdapter.setOnItemClickLitener(companyItemClickListener);
            recyclerView.setAdapter(companySelectAdapter);
        } else if ("PersonSelectActivity".equals(name)) {
            personSelectAdapter = new PersonSelectAdapter(this);
            personSelectAdapter.setOnItemClickLitener(personItemClickListener);
            recyclerView.setAdapter(personSelectAdapter);

            if (from == PersonSelectActivity.FROM_DEAL) {
                personSelectAdapter.setShow(true);
            }
        } else if ("ObjectSelectActivity".equals(name)) {
            objectSelectAdapter = new ObjectSelectAdapter(this);
            objectSelectAdapter.setOnItemClickLitener(objectItemClickListener);
            recyclerView.setAdapter(objectSelectAdapter);
        } else if ("SpareSelectActivity".equals(name)) {
            spareSelectAdapter = new SpareSelectAdapter(this);
            spareSelectAdapter.setOnItemClickLitener(spareItemClickListener);
            recyclerView.setAdapter(spareSelectAdapter);
        } else if ("NewsFragment".equals(name)) {
            newsMsgAdapter = new NewsMsgAdapter(this);
            newsMsgAdapter.setSwipe(false);
            newsMsgAdapter.setOnItemClickLitener(messageItemClickListener);
            recyclerView.setAdapter(newsMsgAdapter);
        } else if (from == 999) {
            recyclerView.setVisibility(View.GONE);
            listview.setVisibility(View.VISIBLE);
            initBottomCheckPannel();
        } else if (from == 998) {
            thisCompanyType = StringUtils.value(getIntent().getStringExtra("thisCompanyType"));
            recyclerView.setVisibility(View.VISIBLE);
            listview.setVisibility(View.GONE);
            initBottomCheckPannel();
        } else if (from == 997) {
            thisCompanyType = StringUtils.value(getIntent().getStringExtra("thisCompanyType"));
            LogUtil.e("thisCompanyType------------取值：" + thisCompanyType);
            recyclerView.setVisibility(View.GONE);
            listview.setVisibility(View.VISIBLE);
            initBottomCheckPannel();
        }
        searchCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        searchEdit.setFilters(new InputFilter[]{AppHelper.emojiFilter});
        searchEdit.setOnEditorActionListener(this);
    }

    BaseRecyclerViewAdapter.OnItemClickLitener companyItemClickListener = new BaseRecyclerViewAdapter.OnItemClickLitener() {
        @Override
        public void onItemClick(View view, int position) {
            CompanySelectBean.Rows bean = companySelectAdapter.getItem(position);
            Intent intent = new Intent();
            intent.putExtra("companyName", bean.getServerName());
            intent.putExtra("bindFlag", bean.getBindFlag());
            intent.putExtra("companyCode", bean.getCompanyCode());
            setResult(RESULT_OK, intent);
            finish();
        }
    };
    BaseRecyclerViewAdapter.OnItemClickLitener personItemClickListener = new BaseRecyclerViewAdapter.OnItemClickLitener() {
        @Override
        public void onItemClick(View view, int position) {
            SponsorBean.Rows bean = personSelectAdapter.getItem(position);
            Intent intent = new Intent();
            intent.putExtra("name", bean.getName());
            intent.putExtra("employeeId", bean.getEmployeeId());
            setResult(RESULT_OK, intent);
            finish();
        }
    };
    BaseRecyclerViewAdapter.OnItemClickLitener objectItemClickListener = new BaseRecyclerViewAdapter.OnItemClickLitener() {
        @Override
        public void onItemClick(View view, int position) {
            ScannerAsset bean = objectSelectAdapter.getItem(position);
            Intent intent = new Intent();
            intent.putExtra("name", bean.getAssetName());
            intent.putExtra("hardwareId", bean.getAssetId());
            intent.putExtra("ownerCode", bean.getOwnerCode());
            intent.putExtra("serverName", bean.getServerName());
            intent.putExtra("bindFlag", bean.getBindFlag());
            setResult(RESULT_OK, intent);
            finish();
        }
    };
    BaseRecyclerViewAdapter.OnItemClickLitener spareItemClickListener = new BaseRecyclerViewAdapter.OnItemClickLitener() {
        @Override
        public void onItemClick(View view, int position) {
            SpareSearchBean.Rows item = spareSelectAdapter.getItem(position);
            Intent intent = new Intent();
            intent.putExtra("hardName", item.getAssetName());
            intent.putExtra("spareId", item.getStoreId());
            setResult(RESULT_OK, intent);
            finish();
        }
    };
    BaseRecyclerViewAdapter.OnItemClickLitener messageItemClickListener = new BaseRecyclerViewAdapter.OnItemClickLitener() {
        @Override
        public void onItemClick(View view, int position) {
            MsgBean.RowsBean bean = newsMsgAdapter.getItem(position);
            if (TextUtils.isEmpty(bean.getType())) {
                Conversation conversation = bean.getConversation();
                String targetId = conversation.getTargetId();
                if (targetId.equals(RongIM.getInstance().getCurrentUserId())) {
                    showCenterInfoMsg(getResources().getString(R.string.Cant_chat_with_yourself));
                } else {
                    String title = "";
                    Conversation.ConversationType type = conversation.getConversationType();
                    if (conversation.getConversationType() == Conversation.ConversationType.GROUP) {

                    } else if (conversation.getConversationType() == Conversation.ConversationType.PRIVATE) { //单聊
                        UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(conversation.getTargetId());
                        if (userInfo != null) {
                            title = RongUserInfoManager.getInstance().getUserInfo(targetId).getName();
                        }
                    }
                    RongIM.getInstance().startConversation(mContext, type, targetId, title);
                }
            } else {
                if ("7".equals(bean.getType().substring(0, 1))) { //企业申请
                    // MessageCompanyActivity.openActivity(getContext());
                } else {
                    MessageDealActivity.OpenActivity(CommonSearchActivity.this, bean.getType(), editSearch);
                }
            }
        }
    };

    //初始化列表控件
    public void initBottomCheckPannel() {
        if (from_type == 1) {
            pannelBottom.setVisibility(View.VISIBLE);
            rlvBottomContact.setLayoutManager(new LinearLayoutManager(this, LinearLayout.HORIZONTAL, false));
            bottomListAdapter = new StartChatListAdapter(this, companyType);
            rlvBottomContact.setAdapter(bottomListAdapter);
            btnCommit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    TranspaintActivity.openActivity(CommonSearchActivity.this);
                   /* EventBus.getDefault().post(new CommitMemberEvent(CommitMemberEvent.COMMIT_MEMBER_EVENT));*/
                }
            });
            initBottomContactList();
        } else {
            pannelBottom.setVisibility(View.GONE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onRefreshName(ContactCheckEvent event) {
        initBottomContactList();
        if (sortContactAdapter != null) {
            sortContactAdapter.notifyDataSetChanged();
        }
    }


    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onClosePage(ChatListCloseEvent event) {
        finish();
    }

    //初始化底部控件数据
    public void initBottomContactList() {
        bottomListAdapter.setData(AppHelper.getCheckContactList());
        String commitText = "";
        if (UtilList.getCount(AppHelper.getCheckContactList()) == 0) {
            commitText = "确定";
        } else {
            commitText = "确定(" + UtilList.getCount(AppHelper.getCheckContactList()) + ")";
        }
        btnCommit.setText(commitText);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            // 先隐藏键盘
            ((InputMethodManager) searchEdit.getContext().getSystemService(Context.INPUT_METHOD_SERVICE))
                    .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            //实现自己的搜索逻辑
            String s = searchEdit.getText().toString().trim();
            searchData(s);
            return true;
        }
        return false;
    }

    private void searchData(String s) {
        if (TextUtils.isEmpty(s))
            return;
        editSearch = s;
        HashMap<String, String> map = new HashMap<>();
        if ("CompanySelectActivity".equals(name)) {
            if (from == FROM_SENDER) {
                map.put("useFlag", "1");
                map.put("type", "1");
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                map.put("serverName", editSearch);
                ServiceRequestManager.getManager().getWorkSendCompany(this, JsonMapUtil.mapToJson(map), companyHttpListener);
            } else {
                if (from == FROM_DEALER) {
                    map.put("exeType", "1");
                    map.put("serverName", editSearch);
                } else if (from == FROM_ASSIGNER) {
                    map.put("bindFlag", "1");
                }
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                ServiceRequestManager.getManager().workOrderAssign(this, JsonMapUtil.mapToJson(map), companyHttpListener);
            }
        } else if ("PersonSelectActivity".equals(name)) {
            if (from == FROM_LAUNCH) {
                map.put("bindFlag", bindFlag);
                map.put("synCode", synCode);
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("name", editSearch);
                ServiceRequestManager.getManager().getWorkSendPerson(this, JsonMapUtil.mapToJson(map), personHttpListener);
            } else if (from == FROM_COMPLAIN_DEAL) { // 投诉 处理
            } else {
                if ("1".equals(companyType)) {//业主
                    map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                    map.put("name", editSearch);
                    if (from == FROM_PROBLEM_ASSIGN) {
                        map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                    }
                } else if ("2".equals(companyType)) {//服务商
                    map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                    map.put("name", editSearch);
                    if (from == FROM_PROBLEM_ASSIGN) {
                        map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                    }
                }
                ServiceRequestManager.getManager().getWorkDealPerson(this, JsonMapUtil.mapToJson(map), personHttpListener);
            }
        } else if ("ObjectSelectActivity".equals(name)) {
            if ("1".equals(companyType)) {//业主
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
                map.put("ownerCode", ownerBean.getRows().getOwnerCode());
                map.put("assetName", editSearch);
                map.put("typeStatus", "1");
            } else if ("2".equals(companyType)) {//服务商
                map.put("ownerCode", ownerCode);
                map.put("contractId", contractId);
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
                map.put("serviceProviderCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("assetName", editSearch);
                map.put("typeStatus", "1");
            }
            ServiceRequestManager.getManager().getWorkAsset(this, JsonMapUtil.mapToJson(map), objectHttpListener);
        } else if ("SpareSelectActivity".equals(name)) {
            if ("1".equals(companyType)) {
                map.put("currentUserId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("currentUserId", serviceLoginBean.getRows().getEmployeeId());
            }
            map.put("searchName", editSearch);
            ServiceRequestManager.getManager().getSpareSelectList(this, JsonMapUtil.mapToJson(map), spareListener);
        } else if ("NewsFragment".equals(name)) {
            msgList = new ArrayList<>();

            if ("1".equals(companyType)) {
                map.put("receiverCompanyCode", ownerBean.getRows().getOwnerCode());
                map.put("receiverId", ownerBean.getRows().getEmployeeId());
            } else if ("2".equals(companyType)) {
                map.put("receiverCompanyCode", serviceLoginBean.getRows().getServiceProviderCode());
                map.put("receiverId", serviceLoginBean.getRows().getEmployeeId());
            }
            map.put("content", editSearch);
            ServiceRequestManager.getManager().getUnreadMsg(this, JsonMapUtil.mapToJson(map), messageListener);

            // 获取聊天消息
            RongIM.getInstance().getConversationList(new RongIMClient.ResultCallback<List<Conversation>>() {
                @Override
                public void onSuccess(List<Conversation> conversations) {
                    List<MsgBean.RowsBean> list = new ArrayList<>();
                    if (conversations != null) {
                        for (Conversation conversation : conversations) {
                            if (conversation.getConversationType() == Conversation.ConversationType.GROUP) {
                                Group group = RongUserInfoManager.getInstance().getGroupInfo(conversation.getTargetId());
                                if (group != null &&group.getName().contains(editSearch)) {
                                    MsgBean.RowsBean bean = new MsgBean.RowsBean();
                                    bean.setConversation(conversation);
                                    list.add(bean);
                                }
                            } else if (conversation.getConversationType() == Conversation.ConversationType.PRIVATE) { //单聊
                                UserInfo userInfo = RongUserInfoManager.getInstance().getUserInfo(conversation.getTargetId());
                                if (userInfo != null && userInfo.getName().contains(editSearch)) {
                                    MsgBean.RowsBean bean = new MsgBean.RowsBean();
                                    bean.setConversation(conversation);
                                    list.add(bean);
                                }
                            }
                        }
                    }
                    msgList.addAll(0, list);
                    newsMsgAdapter.setData(msgList);
                }

                @Override
                public void onError(RongIMClient.ErrorCode errorCode) {

                }
            });

        } else if (from == 999) {//从联系人跳转过来
            ServiceRequestManager manager = ServiceRequestManager.getManager();
            String json = "";
            if ("1".equals(companyType)) {
                json = new Gson().toJson(new EmpInfoJsonBean(ownerBean.getRows().getEmployeeId(), editSearch, 1, 100));
            } else if ("2".equals(companyType)) {
                json = new Gson().toJson(new EmpInfoJsonBean(serviceLoginBean.getRows().getEmployeeId(), editSearch, 1, 100));
            }
            manager.queryContactByCharacter(this, json, contactListener);
        } else if (from == 998) {//从按好友企业查看页面条转过来
            ServiceRequestManager manager = ServiceRequestManager.getManager();
            String json = "";
            if ("1".equals(companyType)) {
                json = new Gson().toJson(new EnterpriseOwnerBean(ownerBean.getRows().getOwnerCode(), editSearch, 1, 10000));
            } else if ("2".equals(companyType)) {
                json = new Gson().toJson(new EnterpriseServiceBean(serviceLoginBean.getRows().getServiceProviderCode(),
                        editSearch, 1, 10000));
            }
            manager.queryFriendCompany(this, json, friendcompany);
        } else if (from == 997) {//查询该企业下面好友信息 筛选
            ServiceRequestManager manager = ServiceRequestManager.getManager();
            map.put("companyCode", companyCode);
            map.put("page", StringUtils.value(1));
            map.put("rows", "1000");
            map.put("name", editSearch);
            manager.queryFriendCompanyContact(this, JsonMapUtil.mapToJson(map), friendContact);
            contactPinyinComparator = new ContactPinyinComparator();

        }
    }

    HttpTaskListener spareListener = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            SpareSearchBean bean = new Gson().fromJson(result, SpareSearchBean.class);
            if (bean.getMessage().getCode() == 200) {
                if (bean.getRows() != null && bean.getRows().size() != 0) {
                    stateLayout.showContentView();
                    spareSelectAdapter.setData(bean.getRows());
                } else {
                    stateLayout.showSearchEmptView();
                }
            }
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };
    HttpTaskListener friendContact = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            CompanyContactBean bean = new Gson().fromJson(result, CompanyContactBean.class);
            if (bean != null) {
                contactList = bean.getRows();
                if (UtilList.getCount(contactList) > 0) {
                    contactList = fillContactPingYing(contactList);
                    Collections.sort(contactList, contactPinyinComparator);
                    sortContactAdapter = new SortContactAdapter(CommonSearchActivity.this, from_type, thisCompanyType, contactList);
                    listview.setAdapter(sortContactAdapter);
                }

            }
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };
    HttpTaskListener friendcompany = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            friendCompanyAdapter = new FriendCompanyAdapter(mContext, from_type, thisCompanyType);
            recyclerView.setAdapter(friendCompanyAdapter);
            EnterpriseBean bean = new Gson().fromJson(result, EnterpriseBean.class);
            if (bean.getRows() != null) {
                friendCompanyAdapter.addAll(bean.getRows());
            }
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };
    HttpTaskListener objectHttpListener = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            AssetSearchBean bean = new Gson().fromJson(result, AssetSearchBean.class);
            if (bean.getMessage().getCode() == 200) {
                objectSelectAdapter.setData(bean.getRows());
                if (bean.getRows() != null && bean.getRows().size() != 0) {
                    stateLayout.showContentView();
                } else {
                    stateLayout.showSearchEmptView();
                }
            }
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };
    HttpTaskListener personHttpListener = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            SponsorBean bean = new Gson().fromJson(result, SponsorBean.class);
            if (bean.getMessage().getCode() == 200) {
                personSelectAdapter.setData(bean.getRows());
                if (bean.getRows() != null && bean.getRows().size() != 0) {
                    stateLayout.showContentView();
                } else {
                    stateLayout.showSearchEmptView();
                }
            }
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };
    HttpTaskListener companyHttpListener = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            CompanySelectBean bean = new Gson().fromJson(result, CompanySelectBean.class);
            if (bean.getMessage().getCode() == 200) {
                companySelectAdapter.setData(bean.getRows());
                if (bean.getRows() != null && bean.getRows().size() != 0) {
                    stateLayout.showContentView();
                } else {
                    stateLayout.showSearchEmptView();
                }
            }
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };
    HttpTaskListener contactListener = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            contactPingyinComparator = new ContactPingyinComparator();
            AllContactBean bean = new Gson().fromJson(result, AllContactBean.class);
            List<Contact> contactList = bean.getRows();
            if (contactList != null && contactList.size() != 0) {
                stateLayout.showContentView();
                contactList = filledPingYing(contactList);
                Collections.sort(contactList, contactPingyinComparator);
            } else {
                stateLayout.showSearchEmptView();
            }
            sortContactAdapter = new SortContactAdapter(CommonSearchActivity.this, from_type, companyType, contactList);
            listview.setAdapter(sortContactAdapter);
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };
    HttpTaskListener messageListener = new HttpTaskListener() {
        @Override
        public void onSuccess(int requestId, String result) {
            MsgBean msgBean = new Gson().fromJson(result, MsgBean.class);
            if (msgBean.getMessage().getCode() == 200) {
                List<MsgBean.RowsBean> list = new ArrayList<>();
                for (String key : msgBean.getRows().keySet()) {
                    MsgBean.RowsBean rowsBean = msgBean.getRows().get(key);
                    rowsBean.setType(key);
                    list.add(rowsBean);
                }
                msgList.addAll(list);
                newsMsgAdapter.setData(msgList);
                if (msgList.size() != 0) {
                    stateLayout.showContentView();
                } else {
                    stateLayout.showSearchEmptView();
                }
            } else {
                showCenterInfoMsg(msgBean.getMessage().getMessage());
            }
        }

        @Override
        public void onException(int requestId, String code) {
            stateLayout.showErrorView();
        }
    };


    //转拼音
    private List<Contact> fillContactPingYing(List<Contact> contactList) {
        for (int i = 0; i < contactList.size(); i++) {
            Contact contact = contactList.get(i);
            if (contact != null) {
                String name = StringUtils.value(contact.getEmployeeName());
                //汉字转换成拼音
                String pinyin = PinyinUtils.getPingYin(name);
                String sortString = pinyin.substring(0, 1).toUpperCase();
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    contact.setLetter(sortString.toUpperCase());
                } else {
                    contact.setLetter("#");
                }
            }

        }
        return contactList;
    }

    private List<Contact> filledPingYing(List<Contact> contactList) {

        for (int i = 0; i < contactList.size(); i++) {
            Contact appEmployee = contactList.get(i);
            if (appEmployee != null) {
                String name = appEmployee.getName();
                //汉字转换成拼音
                String pinyin = PinyinUtils.getPingYins(name);

                // String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(name.toCharArray()[0]);
                String sortString = pinyin.substring(0, 1).toUpperCase();
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]")) {
                    appEmployee.setLetter(sortString.toUpperCase());
                } else {
                    appEmployee.setLetter("#");
                }
            }
        }

        return contactList;
    }

    /**
     * 初始化场景
     */
    private void initial() {
        // 获取上一个界面传入的信息
        mRect = getIntent().getSourceBounds();
        //图片资源 ID
        int mRescourceId = getIntent().getExtras().getInt("search_image");

        // 获取上一个界面中，图片的宽度和高度
        mOriginWidth = mRect.right - mRect.left;
        mOriginHeight = mRect.bottom - mRect.top;

        // 设置 ImageView 的位置，使其和上一个界面中图片的位置重合
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(mOriginWidth, mOriginHeight);
        params.setMargins(mRect.left, mRect.top - getStatusBarHeight(), mRect.right, mRect.bottom);
        mImageView.setLayoutParams(params);

        // 设置 ImageView 的图片和缩放类型
        mImageView.setImageResource(mRescourceId);
        mImageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

        // 根据上一个界面传入的图片资源 ID，获取图片的 Bitmap 对象。
        BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(mRescourceId);
        Bitmap bitmap = bitmapDrawable.getBitmap();

        // 计算图片缩放比例和位移距离
        getBundleInfo(bitmap);

    }

    /**
     * 计算图片缩放比例，以及位移距离
     */
    private void getBundleInfo(Bitmap bitmap) {
        // 计算图片缩放比例，并存储在 bundle 中
        if (bitmap.getWidth() >= bitmap.getHeight()) {
            mScaleBundle.putFloat(SCALE_WIDTH, (float) mScreenWidth / mOriginWidth);
            mScaleBundle.putFloat(SCALE_HEIGHT, (float) bitmap.getHeight() / mOriginHeight);
        } else {
            mScaleBundle.putFloat(SCALE_WIDTH, (float) bitmap.getWidth() / mOriginWidth);
            mScaleBundle.putFloat(SCALE_HEIGHT, (float) mScreenHeight / mOriginHeight);
        }
        // 计算位移距离，并将数据存储到 bundle 中
        mTransitionBundle.putFloat(TRANSITION_X, mScreenWidth / 2 - (mRect.left + (mRect.right - mRect.left) / 2));

//        mTransitionBundle.putFloat(TRANSITION_Y, mScreenHeight / 2 - (mRect.top + (mRect.bottom - mRect.top) / 2));
        mTransitionBundle.putFloat(TRANSITION_Y, -(mRect.top - getStatusBarHeight()));
    }

    /**
     * 模拟入场动画
     */
    private void runEnterAnim() {
        mImageView.animate()
                .setInterpolator(DEFAULT_INTERPOLATOR)
                .setDuration(DURATION)
                .scaleX(mScaleBundle.getFloat(SCALE_WIDTH))
                .scaleY(mScaleBundle.getFloat(SCALE_HEIGHT))
                .translationX(mTransitionBundle.getFloat(TRANSITION_X))
                .translationY(mTransitionBundle.getFloat(TRANSITION_Y))
                .start();
        mImageView.setVisibility(View.VISIBLE);

        //add
        mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_EDIT, DURATION);
        mHandler.sendEmptyMessageDelayed(MESSAGE_SHOW_KEYBOARD, DURATION * 2);
    }

    /**
     * 模拟退场动画
     */
    @SuppressWarnings("NewApi")
    private void runExitAnim() {
        //add
        searchLine.setVisibility(View.GONE);
        searchTop.setVisibility(View.GONE);
        mImageView.setVisibility(View.VISIBLE);

        mImageView.animate()
                .setInterpolator(DEFAULT_INTERPOLATOR)
                .setDuration(DURATION)
                .scaleX(1)
                .scaleY(1)
                .translationX(0)
                .translationY(0)
                .withEndAction(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                        overridePendingTransition(0, 0);
                    }
                })
                .start();
    }

    @Override
    public void onBackPressed() {
        // 使用退场动画
        runExitAnim();
    }

    /**
     * 获取屏幕尺寸
     */
    private void getScreenSize() {
        Display display = getWindowManager().getDefaultDisplay();
        Point size = new Point();
        display.getSize(size);
        mScreenWidth = size.x;
        mScreenHeight = size.y;
    }

    /**
     * 获取状态栏高度
     */
    private int getStatusBarHeight() {
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            return getResources().getDimensionPixelSize(resourceId);
        }
        return -1;
    }

    private void showSearchResult() {
        searchEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                //搜索的匹配算法
                Log.d("SearchActivity", " afterTextChanged 调用了 s=" + s.toString());

            }
        });
    }

    public static void OpenActivityFroCompany(Activity activity, View view, Class clazz, int from) {
        Intent intent = new Intent(activity, CommonSearchActivity.class);
        //创建一个rect 对象来存储共享元素的位置信息
        Rect rect = new Rect();
        //获取元素的位置信息
        view.getGlobalVisibleRect(rect);
        //将位置信息附加到intent 上
        intent.setSourceBounds(rect);
        SearchImage customImage = (SearchImage) view;
        intent.putExtra("search_image", customImage.getImageId());
        intent.putExtra("class", clazz);
        intent.putExtra("from", from);
        activity.startActivityForResult(intent, 520);
        //用于屏蔽 activity 默认的转场动画效果
        activity.overridePendingTransition(0, 0);
    }

    public static void OpenActivityForPerson(Activity activity, View view, Class clazz, int from, String bindFlag, String synCode) {
        Intent intent = new Intent(activity, CommonSearchActivity.class);
        //创建一个rect 对象来存储共享元素的位置信息
        Rect rect = new Rect();
        //获取元素的位置信息
        view.getGlobalVisibleRect(rect);
        //将位置信息附加到intent 上
        intent.setSourceBounds(rect);
        SearchImage customImage = (SearchImage) view;
        intent.putExtra("search_image", customImage.getImageId());
        intent.putExtra("class", clazz);
        intent.putExtra("from", from);
        intent.putExtra("bindFlag", bindFlag);
        intent.putExtra("synCode", synCode);
        activity.startActivityForResult(intent, 520);
        //用于屏蔽 activity 默认的转场动画效果
        activity.overridePendingTransition(0, 0);
    }

    public static void OpenActivityForObject(Activity activity, View view, Class clazz, int from, String ownerCode, String contractId) {
        Intent intent = new Intent(activity, CommonSearchActivity.class);
        //创建一个rect 对象来存储共享元素的位置信息
        Rect rect = new Rect();
        //获取元素的位置信息
        view.getGlobalVisibleRect(rect);
        //将位置信息附加到intent 上
        intent.setSourceBounds(rect);
        SearchImage customImage = (SearchImage) view;
        intent.putExtra("search_image", customImage.getImageId());
        intent.putExtra("class", clazz);
        intent.putExtra("from", from);
        intent.putExtra("ownerCode", ownerCode);
        intent.putExtra("contractId", contractId);
        activity.startActivityForResult(intent, 520);
        //用于屏蔽 activity 默认的转场动画效果
        activity.overridePendingTransition(0, 0);
    }

    /**
     * 从联系人中跳转过去
     *
     * @param activity     上下文
     * @param view         点击的view
     * @param clazz        targeClass
     * @param from         从哪个页面跳转过去的
     * @param thisFromType 发起聊天和追加群成员  thisFromType = 1; 联系人列表页面跳转过来的时候  thisFromType = 0;
     */
    public static void OpenActivityFromContact(Activity activity, View view, Class clazz, int from, int thisFromType, String thisCompanyType) {
        Intent intent = new Intent(activity, CommonSearchActivity.class);
        //创建一个rect 对象来存储共享元素的位置信息
        Rect rect = new Rect();
        //获取元素的位置信息
        view.getGlobalVisibleRect(rect);
        //将位置信息附加到intent 上
        intent.setSourceBounds(rect);
        SearchImage customImage = (SearchImage) view;
        intent.putExtra("search_image", customImage.getImageId());
        intent.putExtra("class", clazz);
        intent.putExtra("from", from);
        intent.putExtra("from_type", thisFromType);
        intent.putExtra("thisCompanyType", thisCompanyType);
        LogUtil.e("from_type------------：" + thisFromType);
        LogUtil.e("thisCompanyType------------：" + thisCompanyType);
        activity.startActivity(intent);
        //用于屏蔽 activity 默认的转场动画效果
        activity.overridePendingTransition(0, 0);
    }

    /**
     * 从选择备件中跳转过去
     *
     * @param activity 上下文
     * @param view     点击的view
     * @param clazz    targeClass
     * @param from     从哪个页面跳转过去的
     */
    public static void OpenActivityFromSpare(Activity activity, View view, Class clazz, int from) {
        Intent intent = new Intent(activity, CommonSearchActivity.class);
        //创建一个rect 对象来存储共享元素的位置信息
        Rect rect = new Rect();
        //获取元素的位置信息
        view.getGlobalVisibleRect(rect);
        //将位置信息附加到intent 上
        intent.setSourceBounds(rect);
        SearchImage customImage = (SearchImage) view;
        intent.putExtra("search_image", customImage.getImageId());
        intent.putExtra("class", clazz);
        intent.putExtra("from", from);
        activity.startActivityForResult(intent, 520);
        //用于屏蔽 activity 默认的转场动画效果
        activity.overridePendingTransition(0, 0);
    }

    /**
     * 从好友企业联系人中跳转过去
     *
     * @param activity        上下文
     * @param view            点击的view
     * @param clazz           targeClass
     * @param from            从哪个页面跳转过去的
     * @param companyCode     公司code
     * @param thisFromType    发起聊天和追加群成员  thisFromType = 1; 联系人列表页面跳转过来的时候  thisFromType = 0;
     * @param thisCompanyType 跳转过来的公司的类型
     */
    public static void OpenActivityFromFriendCompanyContact(Activity activity, View view, Class clazz, int from, String companyCode, int thisFromType, String thisCompanyType) {
        Intent intent = new Intent(activity, CommonSearchActivity.class);
        //创建一个rect 对象来存储共享元素的位置信息
        Rect rect = new Rect();
        //获取元素的位置信息
        view.getGlobalVisibleRect(rect);
        //将位置信息附加到intent 上
        intent.setSourceBounds(rect);
        SearchImage customImage = (SearchImage) view;
        intent.putExtra("search_image", customImage.getImageId());
        intent.putExtra("class", clazz);
        intent.putExtra("from", from);
        intent.putExtra("companyCode", companyCode);
        intent.putExtra("from_type", thisFromType);// TODO: 2017/12/15 判断是从联系人跳转过来的还是消息跳转过来的
        intent.putExtra("thisCompanyType", thisCompanyType);
        LogUtil.e("from_type------------：" + thisFromType);
        LogUtil.e("thisCompanyType------------入参：" + thisCompanyType);
        activity.startActivity(intent);
        //用于屏蔽 activity 默认的转场动画效果
        activity.overridePendingTransition(0, 0);
    }


    public static void OpenActivityFromMessage(Activity activity, View view, Class clazz) {
        Intent intent = new Intent(activity, CommonSearchActivity.class);
        //创建一个rect 对象来存储共享元素的位置信息
        Rect rect = new Rect();
        //获取元素的位置信息
        view.getGlobalVisibleRect(rect);
        //将位置信息附加到intent 上
        intent.setSourceBounds(rect);
        SearchImage customImage = (SearchImage) view;
        intent.putExtra("search_image", customImage.getImageId());
        intent.putExtra("class", clazz);
        activity.startActivity(intent);
        //用于屏蔽 activity 默认的转场动画效果
        activity.overridePendingTransition(0, 0);
    }

}
